package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Department;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    //查询全部方法
    //@RequiredPermission(name = "部门列表",expression = "department:list")
    @RequiresPermissions(value = {"department:list","部门列表"},logical=Logical.OR)
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        // 测试(统一处理异常):
        //int i=1/0;
        PageInfo pageResult = departmentService.query(qo);
        model.addAttribute("pageResult", pageResult);
        return "department/list";
    }

    //处理删除请求
    //@RequiredPermission(name = "部门删除",expression = "department:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        //因为是异步请求 , 报错在浏览器可以看 因为不会跳 因为是异步提交的
        //try {
            if (id != null) {
                departmentService.deleteByPrimaryKey(id);
            }
            return new JsonResult(true,"删除成功");
//        }catch (Exception e){
//            return new JsonResult(false,"删除失败");
//        }
    }
//
//    //新增 或 修改  input
//    @RequestMapping("/input")
//    public String input(Long id, Model model) {
//        if (id != null) {
//            //表示去修改
//            Department department = departmentService.selectByPrimaryKey(id);
//            model.addAttribute("department", department);
//        }
//        return "department/input";// 让 浏览器重新 发一次请求 跳转到input 页面
//    }

    // 新增 或 修改
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Department department) {

        try {
            if (department.getId() != null) {
                //新增
                departmentService.updateByPrimaryKey(department);

            } else {
                departmentService.insert(department);
            }
            return new JsonResult(true,"成功");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(false,"失败");
    }
    //JsonResult  用 注解  @ResponseBody

}
